package com.zx.tradeclient.ctrl.index5;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.zx.base.ctrl.BaseActivity;
import com.zx.base.ctrl.Constant;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.lazylist.ImageLoader;
import com.zx.base.widget.LoadMoreListView;
import com.zx.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.zx.base.widget.LoadMoreListViewWithProgress;
import com.zx.tradeclient.R;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.entity.SupplyAndWantInfo;

public class WantList {

	private NewsListAdapter newsListAdapter;
	private LoadMoreListViewWithProgress news_view;
	private LoadMoreListView news_listView;
	private ArrayList<SupplyAndWantInfo> newsList = new ArrayList<SupplyAndWantInfo>();
	private int page;
	private TradeApp app;
	private ImageLoader imageLoader;
	private Context content;

	public WantList(final Context context, View view) {
		content = context;
		page = 1;
		imageLoader = ((TradeApp) context.getApplicationContext()).imageLoader;
		init();
		app = (TradeApp) context.getApplicationContext();
		news_view = (LoadMoreListViewWithProgress) view.findViewById(R.id.list);
		news_listView = news_view.getListView();
		newsListAdapter = new NewsListAdapter(context, newsList);
		news_listView.setAdapter(newsListAdapter);
		news_listView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent,
							final View view, int position, long id) {
						Intent intent = new Intent(context,
								WantEditActivity.class);
						intent.putExtra("act", "edit");
						intent.putExtra("wantid", ""
								+ newsList.get(position).getId());
						((BaseActivity) context).startActivity(intent);
					}
				});
		news_listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				// TODO 拖动刷新
				page++;
				goodsListTask();

			}
		});

		goodsListTask();
	}

	public void init() {

		((BaseActivity) content).header_right
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(content,
								WantEditActivity.class);
						content.startActivity(intent);
					}
				});
	}

	public void initview() {
		newsList.clear();
		goodsListTask();
	}

	private static class ViewHolder {
		public TextView title;
		public TextView state;
		public TextView num;
		public TextView price;
		public Button button;
		public Button statechange;
	}

	private class NewsListAdapter extends BaseAdapter {

		private List<SupplyAndWantInfo> topics;
		private LayoutInflater mlinflater;

		public NewsListAdapter(Context context, List<SupplyAndWantInfo> list) {
			this.mlinflater = LayoutInflater.from(context);
			this.topics = list;
		}

		@Override
		public int getCount() {
			return topics.size();
		}

		@Override
		public Object getItem(int position) {
			return Integer.valueOf(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup viewGroup) {
			final SupplyAndWantInfo topic = topics.get(position);
			if (view == null) {
				view = mlinflater.inflate(R.layout.want_list_item, null);
				ViewHolder vh = new ViewHolder();
				vh.title = (TextView) view.findViewById(R.id.list_sandw_title);
				vh.state = (TextView) view.findViewById(R.id.list_sandw_state);
				vh.price = (TextView) view.findViewById(R.id.list_sandw_price);
				vh.num = (TextView) view.findViewById(R.id.list_sandw_num);
				vh.button = (Button) view.findViewById(R.id.list_want_button);
				vh.statechange = (Button) view
						.findViewById(R.id.list_want_button_change);
				view.setTag(vh);
			}
			ViewHolder holder = (ViewHolder) view.getTag();
			holder.title.setText(topic.getTitle());
			if(topic.getState().equals("1")){
				holder.state.setText("已完成");
			}else{
				holder.state.setText("未完成");
			}
			
			holder.price.setText(topic.getPrice());
			holder.num.setText(topic.getNum());

				holder.statechange.setText("更改");
				holder.statechange.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 停止
						changeState(position);
					}
				});


			holder.button.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 删除
					deleteTask(topic.getId(), position);
				}
			});

			return view;
		}
	}

	private void goodsListTask() {

		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "supplyDemandList");
		map.put("userId", app.user.getId());
		map.put("way", "00");
		map.put("currentPage", "" + page);
		map.put("rowCountPerPage", "10");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJson(response);
				Log.d("TAG",response.toString());
			}

			@Override
			public void onFailure(Throwable e) {
				Toast toast = Toast.makeText(content, "网络超时。",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			}

			private void parseJson(JSONObject response) {
				try {
					String currentPage = response.getString("currentPage");
					String totalPage = response.getString("totalPage");
					if (Constant.debug)
						Log.d("stop", currentPage);
					if (Constant.debug)
						Log.d("stop", totalPage);
					if (currentPage.equals(totalPage)) {
						news_listView.loadComplete(false);
					}
					JSONArray list = new JSONArray(response
							.getString("dataList"));
					for (int i = 0; i < list.length(); i++) {
						SupplyAndWantInfo one = new SupplyAndWantInfo();
						JSONObject goods = list.getJSONObject(i);
						one.setNum(goods.getString("num"));
						one.setPrice(goods.getString("price"));
						one.setState(goods.getString("state"));
						one.setTitle(goods.getString("productname"));
						one.setId(goods.getString("id"));
						newsList.add(one);
					}
					newsListAdapter.notifyDataSetChanged();
					news_view.show();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void deleteTask(String id, final int removeid) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "infoDelete");
		map.put("userId", app.user.getId());
		map.put("id", id);
		map.put("type", "3");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJson(response);

			}

			@Override
			public void onFailure(Throwable e) {
				Toast toast = Toast.makeText(content, "网络超时。",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			}

			private void parseJson(JSONObject response) {
				try {
					String succeed = response.getString("succeed");
					if (succeed.equals("000")) {
						newsList.remove(removeid);
						Toast toast = Toast.makeText(content, "删除成功。",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					} else {
						Toast toast = Toast.makeText(content, "删除失败。",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
					newsListAdapter.notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void changeState(final int id) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "askBuyStateModify");
		map.put("id", newsList.get(id).getId());
		if( newsList.get(id).getState().equals("1")){
			map.put("state", "0");
		}else{
			map.put("state", "1");
		}
		
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJson(response);

			}

			@Override
			public void onFailure(Throwable e) {
				Toast toast = Toast.makeText(content, "网络超时。",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			}

			private void parseJson(JSONObject response) {
				try {
					String succeed = response.getString("succeed");
					if (succeed.equals("000")) {
						if(newsList.get(id).getState().equals("1")){
							newsList.get(id).setState("0");
							Toast toast = Toast.makeText(content, "更改成功,开始求购。",
									Toast.LENGTH_SHORT);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();
						}else{
							newsList.get(id).setState("1");
							Toast toast = Toast.makeText(content, "更改成功,停止求购。",
									Toast.LENGTH_SHORT);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();
						}
						
					} else {
						Toast toast = Toast.makeText(content, "更改失败。",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
					newsListAdapter.notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}
}
